package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SkuImagesDao;
import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.SeckillFeignService;
import com.atguigu.gulimall.product.service.SkuInfoService;
import com.atguigu.gulimall.product.service.SkuSaleAttrValueService;
import com.atguigu.gulimall.product.service.SpuInfoDescService;
import com.atguigu.gulimall.product.to.SecKillSkuTo;
import com.atguigu.gulimall.product.vo.SkuItemSaleAttrVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroup;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Resource
    SkuImagesDao skuImagesDao;

    @Resource
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    SeckillFeignService seckillFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 列表
     * * page: 1
     * * limit: 10
     * * key:
     * * catelogId: 0
     * * brandId: 0
     * * min: 0
     * * max: 0
     *
     * @param params
     * @return
     */

    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        //检索的关键字
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((item) -> {
                item.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        //catelogId

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        ;
        //brandId
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        ;
        //min
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            BigDecimal decimal = new BigDecimal(min);

            wrapper.ge("price", decimal);
        }
        ;
        //max
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            BigDecimal decimal = new BigDecimal(max);
            //最大值为0
            if (!(decimal.compareTo(new BigDecimal(0)) == 0))
                wrapper.le("price", decimal);
        }
        ;

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);


        return new PageUtils(page);
    }

    @Override
    public SkuItemVo item(long skuId) {
        /**
         * //1.sku基本信息的获取 pms_sku_info
         *     SkuInfoEntity info;
         *     //2.sku的图片信息 pms_sku_images
         *     List<SkuImagesEntity> images;
         *     //3.获取spu的销售属性组合
         *     List<SkuItemSaleAttrVo> saleAttr;
         *     //获取spu的介绍
         *     SpuInfoDescEntity desp;
         *     //获取spu的规格参数
         *     List<SpuItemAttrGroup>groupAttrs;
         */
        SkuItemVo skuItemVo = new SkuItemVo();
        //1.sku基本信息的获取 pms_sku_info
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = this.baseMapper.selectById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        //2.spu的介绍信息（大图）
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", res.getSpuId()));
            skuItemVo.setDesp(spuInfoDescEntity);
        }, threadPoolExecutor);

        //3.规格参数
        CompletableFuture<Void> baseAttr = infoFuture.thenAcceptAsync((res) -> {
            List<SpuItemAttrGroup> groupAttrs = spuInfoDescService.basicAttr(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
        }, threadPoolExecutor);

        //4.spu的sku销售属性
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            List<SkuItemSaleAttrVo> saleAttr = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttr);
        }, threadPoolExecutor);

        //5.sku的图片信息
        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> imagesEntityList = skuImagesDao.selectList(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            skuItemVo.setImages(imagesEntityList);
        }, threadPoolExecutor);

        //ToDo:6.查询商品的秒杀信息
        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            R seckillInfo = seckillFeignService.querySkuSeckillInfo(skuId + "");

            if (seckillInfo.getCode() == 0) {
                SecKillSkuTo skuTo = seckillInfo.getData(new TypeReference<SecKillSkuTo>() {
                });
                skuItemVo.setSecKillSkuTo(skuTo);
            }
        }, threadPoolExecutor);

        //等到所有异步任务完成以后返回结果
        try {
            //get()阻塞住
            CompletableFuture.allOf(descFuture, baseAttr, saleAttrFuture, imgFuture, secKillFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //catgoryId->pms_attr_group ->attr_group_id->pms_attr_group_relation->attr_id->pms_product_attr_value(spu_id+attr_id)
        //groupName、  attrName、 attrValue;

        return skuItemVo;
    }

    @Override
    public SkuInfoEntity getPrice(Long skuId) {
        return baseMapper.selectOne(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuId));
    }
}